package cn.cjlmonster.demo02.virtual;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * cn.cjlmonster.demo02.virtual
 *
 * @author cjl
 * @project Demo02
 * @date 2022/11/4 20:54
 */
public abstract class BaseDevice implements DefaultLifecycleObserver, Observer<Integer> {

    private static final int REQUEST_TIMEOUT = 3;
    private static final int DELAY_DURATION = 10;

    private final String TAG;

    public final String name;

    public BaseDevice(String name) {
        this.name = name;
        this.TAG = String.format("设备 - %s", name);
        this.random = new Random();
        this.isOnline = true;
        this.randomNumber = getRandomNumber();
        this.randomLiveData = new MutableLiveData<>(this.randomNumber);
    }

    private final Random random;
    private final MutableLiveData<Integer> randomLiveData;

    public MutableLiveData<Integer> getRandomLiveData() {
        return randomLiveData;
    }

    public boolean isOnline;
    public int randomNumber;

    private int getRandomNumber() {
        return random.nextInt(1000);
    }

    private void post(Integer number) {
        randomLiveData.postValue(number);
    }

    public void subscribe(LifecycleOwner owner, androidx.lifecycle.Observer<Integer> observer) {
        owner.getLifecycle().addObserver(this);
        randomLiveData.observe(owner, observer);
    }

    public void unsubscribe(LifecycleOwner owner) {
        dispose();
        owner.getLifecycle().removeObserver(this);
        randomLiveData.removeObservers(owner);
    }

    public void unsubscribe(LifecycleOwner owner, androidx.lifecycle.Observer<Integer> observer) {
        randomLiveData.removeObserver(observer);
        if (!randomLiveData.hasObservers()) {
            dispose();
            owner.getLifecycle().removeObserver(this);
        }
    }

    private Disposable requestDisposable;
    private Disposable delayDisposable;

    public void dispose() {
        if (requestDisposable != null) {
            requestDisposable.dispose();
            requestDisposable = null;
        }
        if (delayDisposable != null) {
            delayDisposable.dispose();
            delayDisposable = null;
        }
    }

    public void requestData() {
        Observable.just(getRandomNumber()).delay(REQUEST_TIMEOUT, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        requestDisposable = d;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        isOnline = integer % 2 == 0;
                        randomNumber = integer;
                        Log.i(TAG, "onNext: randomNumber = " + randomNumber);
                        startDelay();
                        post(randomNumber);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 开启定时
     */
    public void startDelay() {
        dispose(); // 开启定时前，先取消旧的请求
        Observable.just(1).delay(DELAY_DURATION, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .subscribe(this);
    }


    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        Log.i(TAG, "onResume: " + owner);
        requestData();
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        Log.i(TAG, "onPause: " + owner);
        dispose();
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        delayDisposable = d;
    }

    @Override
    public void onNext(@NonNull Integer integer) {
        requestData();
    }

    @Override
    public void onError(@NonNull Throwable e) {

    }

    @Override
    public void onComplete() {

    }
}
